﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Windows.Media.Imaging;

namespace BitmapTagger
{
	/// <summary>
	/// Converts the format of an image
	/// </summary>
	internal class ImageConverter
	{
		/// <summary>
		/// Create a new Image Converter
		/// </summary>
		public ImageConverter() { }

		/// <summary>
		/// Convert a image to another type, all metadata will be converted as well
		/// </summary>
		/// <param name="originalImage">The original's image tagger</param>
		/// <param name="newImagePath">The file path to converted image</param>
		/// <param name="transferExif">Whether or notto transfer the Exif data</param>
		/// <param name="transferXMPExif">Whether or not to transfer the XMP Exif data</param>
		/// <param name="transferXMP">Whether or not to transfer the XMP data</param>
		/// <returns>An Image Tagger for the converted image</returns>
		public BitmapTagger ConvertImageType(BitmapTagger originalImage, string newImagePath, 
			bool transferExif, bool transferXMPExif, bool transferXMP)
		{
			string originalExtension = Path.GetExtension(originalImage.FilePath);
			string newExtension = Path.GetExtension(newImagePath);

			Debug.Assert(ExtensionChecker.IsJPEGExtension(originalExtension) ||
				ExtensionChecker.IsPNGExtension(originalExtension), "Original image is not a supported type");

			Debug.Assert(ExtensionChecker.IsJPEGExtension(newExtension) ||
				ExtensionChecker.IsPNGExtension(newExtension), "New image is not a support type");

			using (Stream originalStream = File.OpenRead(originalImage.FilePath))
			{
				BitmapCreateOptions options = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;
				BitmapDecoder original = BitmapDecoder.Create(originalStream, options, BitmapCacheOption.Default);
				BitmapMetadata metadata = original.Frames[0].Metadata.Clone() as BitmapMetadata;
				BitmapEncoder newFileEncoder;

				if (ExtensionChecker.IsPNGExtension(newExtension))
					newFileEncoder = new PngBitmapEncoder();
				else if (ExtensionChecker.IsJPEGExtension(newExtension))
					newFileEncoder = new JpegBitmapEncoder();
				else
					throw new Exception("Unknown file type");

				newFileEncoder.Frames.Add(BitmapFrame.Create(original.Frames[0], original.Frames[0].Thumbnail, metadata, original.Frames[0].ColorContexts));


				using (Stream outputFile = File.Open(newImagePath, FileMode.Create, FileAccess.ReadWrite))
				{
					newFileEncoder.Save(outputFile);
				}

				BitmapTagger convertedImageTagger = BitmapTagger.Create(newImagePath);

				originalImage.CopyTags(convertedImageTagger);

				convertedImageTagger.Save(transferExif, transferXMPExif, transferXMP);

				return convertedImageTagger;
			}

			
		}
	}
}
